package server

import (
	"fmt"
	"github.com/patrickmn/go-cache"
	"log"
	"quantization_trading/src/models"
	"quantization_trading/src/mycache"
	"quantization_trading/src/util"
)
//初始化账号
func StartAccount()  {
	account_list , err := models.FindAllAccount()
	if err != nil{
		log.Println("启动账号模块异常")
	}else {
		key := fmt.Sprintf("%s_user", "hl")
		mycache.AccountCache.Set(key,account_list,cache.NoExpiration)
	}
}

//添加账号
func AddAccount(account models.Account) int {
	//key := fmt.Sprintf("%s_account", account.UserName)
	key := fmt.Sprintf("%s_user", "hl")
	accounts := []models.Account{}
	if x, found := mycache.AccountCache.Get(key); found {
		accounts = x.([]models.Account)
		for _,ac := range accounts{
			if ac.AccountName == account.AccountName{
				return util.ADD_HAVE_ACCOUNT
			}
		}
	}
	accounts = append(accounts, account)
	mycache.AccountCache.Set(key,accounts,cache.NoExpiration)
	return models.AddAccount(&account)
}

//删除账号
func DelAccount(account models.Account) int {
	//key := fmt.Sprintf("%s_account", account.UserName)
	key := fmt.Sprintf("%s_user", "hl")
	accounts := []models.Account{}
	new_accounts := []models.Account{}
	is_exist :=false
	if x, found := mycache.AccountCache.Get(key); found {
		accounts = x.([]models.Account)
		for _,ac := range accounts{
			if ac.AccountName != account.AccountName{
				new_accounts = append(new_accounts, ac)
			}else {
				is_exist = true
			}
		}
	}
	mycache.AccountCache.Set(key,new_accounts,cache.NoExpiration)
	if is_exist {
		return models.DelAccount(&account)
	}else {
		return util.DEL_ERROR_ACCOUNT
	}
}

